package com.example.friendcash.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.friendcash.BaseApplication;
import com.example.friendcash.R;
import com.example.friendcash.database.core.Event;
import com.example.friendcash.database.services.interfaces.IEventService;
import com.example.friendcash.database.services.interfaces.IFriendService;
import com.example.friendcash.database.services.interfaces.IServiceFactory;
import com.example.friendcash.parameters.IntentConstants;
import com.example.friendcash.utils.functions.IIn;

import java.util.ArrayList;
import java.util.List;

import static com.example.friendcash.utils.collections.Sequences.each;

public class MainActivity extends AbsMenuActivity {

    public final static String EVENT_POSITION = "EVENT_POSITION";

    private IServiceFactory serviceFactory;

    private final List<Event> events = new ArrayList<Event>();
    private EventAdapter adapter;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.main);
        setupOverflowMenu(R.menu.main, findViewById(R.id.main_menu));
        serviceFactory = BaseApplication.getInstance().getServiceFactory();
        final View newEventButton = findViewById(R.id.main_new_event);
        newEventButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Intent intent = new Intent(MainActivity.this, NewEventActivity.class);
                startActivityForResult(intent, 0);
            }
        });
        final ListView listView = (ListView) findViewById(R.id.events);
        adapter = new EventAdapter(this, android.R.layout.simple_list_item_1, events);
        listView.setAdapter(adapter);
        initEventsItems();
    }

    private final class EventAdapter extends ArrayAdapter<Event> {

        public EventAdapter(Context context, int resource, List<Event> objects) {
            super(context, resource, objects);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final UIHolder uiHolder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.event_listview_item, parent, false);
                uiHolder = UIHolder.createUIHolder(convertView);
                convertView.setTag(uiHolder);
            } else {
                uiHolder = (UIHolder) convertView.getTag();
            }
            final Event event = events.get(position);
            uiHolder.provideValues(event);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    BaseApplication.getInstance().setEntityId(event.id);
                    final Intent intent = new Intent(MainActivity.this, EventActivity.class);
                    intent.putExtra("EVENT_POSITION", position);
                    startActivity(intent);
                }
            });
            return convertView;
        }

        @Override
        public Event getItem(int position) {
            return events.get(position);
        }

        @Override
        public int getCount() {
            return events.size();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            final IEventService eventService = serviceFactory.createEventService();
            final long addedEventId = eventService.addEvent(createEvent(data));
            final Event event = eventService.getEventById(addedEventId);
            events.add(event);
            adapter.notifyDataSetChanged();
        }
    }

    private void initEventsItems() {
        final IEventService eventService = serviceFactory.createEventService();
        final IFriendService friendService = serviceFactory.createFriendService();
        final List<Event> updatedEvents = each(eventService.getAllEvents(), new IIn<Event>() {
            @Override
            public void in(Event event) {
                event.peopleNumber = friendService.getAllFriends(event.id).size();
            }
        });
        events.clear();
        events.addAll(updatedEvents);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //initEventsItems();
    }

    private Event createEvent(Intent data) {
        final String eventName = data.getStringExtra(IntentConstants.NAME);
        final String eventComment = data.getStringExtra(IntentConstants.COMMENT);
        return new Event(0, eventName, eventComment);
    }

    private static class UIHolder {

        private final TextView name;
        private final TextView comment;
        private final TextView peopleNumber;

        private UIHolder(TextView name, TextView comment, TextView peopleNumber) {
            this.name = name;
            this.comment = comment;
            this.peopleNumber = peopleNumber;
        }

        public static UIHolder createUIHolder(View view) {
            return new UIHolder(
                    (TextView) view.findViewById(R.id.event_listview_item_name),
                    (TextView) view.findViewById(R.id.event_listview_item_comment),
                    (TextView) view.findViewById(R.id.peopleNumber)
            );
        }

        public void provideValues(Event eventEntity) {
            name.setText(eventEntity.name);
            comment.setText(eventEntity.comment);
            peopleNumber.setText(Integer.toString(eventEntity.peopleNumber));
        }
    }

}
